package com.scyshkj.university.wechat.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Pattern;

/**
 * Created by 唐旭 on 2016/11/22.
 */
public abstract class ServerAddressUtil {

    private ServerAddressUtil() {
    }

    //获取访问网站IP
    public static String getServerAddress(HttpServletRequest request) {
        InetAddress address = null;
        try {
            address = InetAddress.getByName(request.getRemoteHost());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        assert address != null;
        String hostaddress = address.getHostAddress();
        String ipregex = "((25[0-5])|(2[0-4]\\d)|(1\\d\\d)|([1-9]\\d)|\\[1-9])(\\.((25[0-5])|(2[0-4]\\d)|(1\\d\\d)|([1-9]\\d)|\\d)){3}";
        if (Pattern.matches(ipregex, hostaddress)) {
            return hostaddress;
        } else {
            return null;
        }
    }
}
